﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;

public class HUIEventManager : Singleton<HUIEventManager>
{

    public delegate void OnUIEventHandler(HUIEvent uiEvent);

    private HUIEventManager.OnUIEventHandler[] m_uiEventHandlerMap = new HUIEventManager.OnUIEventHandler[512];

    private List<HUIEvent> m_uiEvents = new List<HUIEvent>();

    public bool HasUIEventListener(enUIEventID eventID)
    {
        return this.m_uiEventHandlerMap[(int)eventID] != null;
    }

    public void AddUIEventListener(enUIEventID eventID, HUIEventManager.OnUIEventHandler onUIEventHandler)
    {
        if (this.m_uiEventHandlerMap[(int)eventID] == null)
        {
            this.m_uiEventHandlerMap[(int)eventID] = delegate
            {
            };
            this.m_uiEventHandlerMap[(int)eventID] = (HUIEventManager.OnUIEventHandler)Delegate.Combine(this.m_uiEventHandlerMap[(int)eventID], onUIEventHandler);
        }
        else
        {
            this.m_uiEventHandlerMap[(int)eventID] = (HUIEventManager.OnUIEventHandler)Delegate.Remove(this.m_uiEventHandlerMap[(int)eventID], onUIEventHandler);
            this.m_uiEventHandlerMap[(int)eventID] = (HUIEventManager.OnUIEventHandler)Delegate.Combine(this.m_uiEventHandlerMap[(int)eventID], onUIEventHandler);
        }
    }

    public void RemoveUIEventListener(enUIEventID eventID, HUIEventManager.OnUIEventHandler onUIEventHandler)
    {
        if (this.m_uiEventHandlerMap[(int)eventID] != null)
        {
            this.m_uiEventHandlerMap[(int)eventID] = (HUIEventManager.OnUIEventHandler)Delegate.Remove(this.m_uiEventHandlerMap[(int)eventID], onUIEventHandler);
        }
    }

    public void DispatchUIEvent(HUIEvent uiEvent)
    {
        uiEvent.m_inUse = true;
        HUIEventManager.OnUIEventHandler onUIEventHandler = this.m_uiEventHandlerMap[(int)(uiEvent.m_eventID)];
        if (onUIEventHandler != null)
        {
            onUIEventHandler(uiEvent);
        }
        uiEvent.Clear();
    }

    public void DispatchUIEvent(enUIEventID eventID)
    {
        HUIEvent uIEvent = this.GetUIEvent();
        uIEvent.m_eventID = eventID;
        this.DispatchUIEvent(uIEvent);
    }

    public void DispatchUIEvent(enUIEventID eventID, stUIEventParams par)
    {
        HUIEvent uIEvent = this.GetUIEvent();
        uIEvent.m_eventID = eventID;
        uIEvent.m_eventParams = par;
        this.DispatchUIEvent(uIEvent);
    }

    public HUIEvent GetUIEvent()
    {
        for (int i = 0; i < this.m_uiEvents.Count; i++)
        {
            HUIEvent cUIEvent = this.m_uiEvents[i];
            if (!cUIEvent.m_inUse)
            {
                return cUIEvent;
            }
        }
        HUIEvent cUIEvent2 = new HUIEvent();
        this.m_uiEvents.Add(cUIEvent2);
        return cUIEvent2;
    }

}
